<!--
 * @Description: 动因库
-->
<template>
  <div>
    <el-row class="pubDriver container">
      <el-col style="margin-right:10px;" class="content-left">
        <!-- 按钮与搜索 -->
        <el-row class="handleBox">
          <!-- 左侧按钮 -->
          <el-col :span="18">
            <el-button @click="addOrEditFunc('1')">新增</el-button>
            <el-button @click="addOrEditFunc('2')">编辑</el-button>
            <el-button @click="deleFunc()">删除</el-button>
            <el-button @click="addOrEditFunc('3')">查看</el-button>
            <el-button @click="addOrEditFunc('5')">复制</el-button>
            <el-button @click="referFunc()">引用情况</el-button>
          </el-col>
          <!-- 右侧查询图标 -->
          <el-col :span="6">
            <div class="handleIconBox">
              <!-- 查询弹框 -->
              <el-popover
                placement="left-start"
                trigger="click"
                popper-class="icon_porper"
              >
                <div class="search_porper">
                  <el-form
                    :model="searchForm"
                    ref="searchForm"
                    label-width="100px"
                    label-position="left"
                    size="mini"
                  >
                    <el-form-item label="动因编码：">
                      <el-input
                        v-model="searchForm.driverCode"
                        style="width:150px"
                      ></el-input>
                    </el-form-item>
                    <el-form-item label="动因名称：">
                      <el-input
                        v-model="searchForm.driverName"
                        style="width:150px"
                      ></el-input>
                    </el-form-item>
                  </el-form>
                  <div style="text-align:center;padding:10px">
                    <el-button size="mini" @click="searchFunc">查询</el-button>
                    <el-button
                      size="mini"
                      @click="
                        (searchForm.driverCode = ''),
                          (searchForm.driverName = '')
                      "
                      >重置</el-button
                    >
                  </div>
                </div>
                <i
                  class="iconfont icon-sousuo"
                  title="搜索"
                  slot="reference"
                ></i>
              </el-popover>

              <el-popover
                placement="bottom"
                width="150"
                trigger="click"
                popper-class="icon_porper"
              >
                <div class="operation_checkbox">
                  <el-checkbox-group v-model="checkList">
                    <el-checkbox
                      v-for="item in textData"
                      :label="item.label"
                      :key="item.prop"
                      >{{ item.label }}</el-checkbox
                    >
                  </el-checkbox-group>
                </div>
                <i
                  class="iconfont icon-liebiaoshezhi"
                  title="列表设置"
                  slot="reference"
                ></i>
              </el-popover>
           </div>
          </el-col>
        </el-row>
        <!-- 列表 -->
        <el-table
          ref="multipleTable"
          @row-click="rowClick"
          :data="tableData"
          stripe
        >
          <el-table-column
            width="55"
            type="selection"
            
          ></el-table-column>
          <el-table-column
            prop="driverCode"
            label="动因编码"
            show-overflow-tooltip
            v-if="columnState[0]"
          >
          </el-table-column>
          <el-table-column
            prop="driverName"
            label="动因名称"
            show-overflow-tooltip
            v-if="columnState[1]"
          >
          </el-table-column>

          <el-table-column
            prop="creator"
            label="创建人"
            show-overflow-tooltip
            sortable
            v-if="columnState[2]"
          />
          <el-table-column prop="createdTm" label="创建时间"
          :formatter="row =>(row.createdTm?timeFormat(row.createdTm):'-')"
          sortable
          show-overflow-tooltip
          v-if="columnState[3]">
          </el-table-column>
          <el-table-column
            prop="modifier"
            label="修改人"
            show-overflow-toolti
            sortable
            v-if="columnState[4]"
            :formatter="(row) => row.modifier || '-'"
          ></el-table-column>
          <el-table-column prop="modifiedTm" 
           :formatter="row =>(row.modifiedTm?timeFormat(row.modifiedTm):'-')"
          label="修改时间" show-overflow-tooltip sortable v-if="columnState[5]">
          </el-table-column>
        </el-table>
        <!-- 分页插件 -->
        <pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchForm.page"
          :page-size="searchForm.size"
          @refresh="searchFunc"
          :total="total"
        ></pagination>
      </el-col>
    </el-row>
    <!-- 查看 form保单-->
    <el-dialog
      v-dialogDrag
      :title="titleName"
      :visible.sync="copy"
      width="514px"
    >
      <el-form
        :model="copyForm"
        ref="copy"
        label-width="110px"
        label-position="left"
        :rules="saveFormRules"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="动因编码：" prop="driverCode" required>
              <el-input
                v-model="copyForm.driverCode"
                maxlength="40"
                :disabled="operateType == 2 || operateType == 3"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="动因名称：" prop="driverName" required>
              <el-input
                v-model="copyForm.driverName"
                maxlength="40"
                :disabled="operateType == 3"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="创建人: " prop="creator" required>
              <el-input
                v-model="copyForm.creator"
                maxlength="40"
                :disabled="true"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
                 <el-form-item label="创建时间: " prop="createdTm">
                <el-input
                class="createdTm_input"
                v-model="copyForm.createdTm"
                :readonly="true"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="描述: " prop="descn">
              <el-input
                type="textarea"
                :rows="2"
                v-model="copyForm.descn"
                maxlength="40"
                :disabled="operateType == 3"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="saveFormButton" v-if="operateType != 3"
          >确 定</el-button
        >
        <el-button @click="cancelTne">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 新增,编辑 form保单-->
    <el-dialog
      v-dialogDrag
      :title="titleName"
      :visible.sync="addOrEdit"
      width="514px"
    >
      <el-form
        :model="saveForm"
        ref="saveOrEditRef"
        label-width="110px"
        label-position="left"
        :rules="saveFormRules"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="动因编码：" prop="driverCode">
              <el-input
                v-model="saveForm.driverCode"
                maxlength="40"
                :disabled="operateType == 2 || operateType == 3"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="动因名称：" prop="driverName">
              <el-input
                v-model="saveForm.driverName"
                maxlength="40"
                :disabled="operateType == 3"
              ></el-input>
            </el-form-item>
          </el-col>
          <!--
          <el-col :span="24">
            <el-form-item label="创建人: " prop="creator" required>
              <el-input v-model="saveForm.creator" maxlength="40" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="创建时间: " prop="createdTm">
              <el-date-picker
                class="createdTm_input"
                v-model="saveForm.createdTm"
                type="datetime"
                format="yyyy-MM-dd hh:mm:ss"
                :readonly="true"
              ></el-date-picker>
            </el-form-item>
          </el-col>-->
          <el-col :span="24">
            <el-form-item label="描述: " prop="descn">
              <el-input
                type="textarea"
                :rows="2"
                v-model="saveForm.descn"
                maxlength="40"
                :disabled="operateType == 3"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="saveFormButton(operateType)" v-if="operateType != 3"
          >确 定</el-button
        >
        <el-button @click="cancelTne">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 引用 form保单-->
    <el-dialog
      v-dialogDrag
      title="查看引用情况"
      :visible.sync="seeDialog"
      width="700px"
      top="5%"
    >
      <el-tabs v-model="activeName">
        <el-tab-pane label="动因引用" name="first">
          <div style="padding: 10px 0">
            <el-button @click="refer()">查看</el-button>
          </div>
          <!--列表-->
          <div>
            <el-table ref="multipleRefTable" :data="referData" stripe>
              <el-table-column width="55" type="selection"></el-table-column>
              <el-table-column
                prop="driverCode"
                label="编码"
                show-overflow-tooltip
              >
              </el-table-column>
              <el-table-column
                prop="driverName"
                label="名称"
                show-overflow-tooltip
              >
              </el-table-column>

              <el-table-column
                prop="driverType"
                label="类型"
                show-overflow-tooltip
                :formatter="
                  (row) => (row.driverType == 0 ? '静态动因' : '动态动因')
                "
              >
              </el-table-column>

              <el-table-column
                prop="driverDesc"
                label="描述"
                show-overflow-tooltip
              >
              </el-table-column>
            </el-table>
            <pagination
              @size-change="rehandleSizeChange"
              @current-change="rehandleCurrentChange"
              :current-page="refsearchForm.page"
              :page-size="refsearchForm.size"
              @refresh="referFunc"
              :total="reftotal"
            ></pagination>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <rule-form
      ref="ruleDriverForm"
      :editTheData="editTheData"
      :popupWindowType="popupWindowType"
      :dialogVisibleProps="dialogVisible"
      @getDialogVisible="getDialogVisible"
    ></rule-form>
  </div>
</template>

<script>
import { caPubDriver } from "@/api/index";
import onlyOneSearch from "@/components/onlyOneSearch";
//跳转form表单
import ruleForm from "@/views/caManage/ruleManage/ruleDriver/ruleDriverFormManage";

import moment from "moment";
export default {
  data() {
    return {
      editTheData: {},
      popupWindowType: "",
      dialogVisible: false,
      //表单元素过滤
      textData: [
        { prop: "driverCode", label: "动因编码" },
        { prop: "driverName", label: "动因名称" },
        { prop: "creator", label: "创建人" },
        { prop: "createdTm", label: "创建时间" },
        { prop: "modifier", label: "修改人" },
        { prop: "modifiedTm", label: "修改时间" },
      ], //双向绑定 选择表单展示字段
      checkList: [],
      seeDialog: false,
      activeName: "first",
      //查询时默认条件
      searchForm: {
        page: 1,
        size: 15,
        driverCode: "",
        driverName: "",
      },
      total: 0,
      reftotal: 0,
      //表单提交时保存的数据
      saveFrom: {},
      copyFrom: {},
      //列表数据对象
      tableData: [
        // {
        //   fieldCode: "123",
        //   fieldName: "123",
        //   creator: "123",
        //   createdTm: 1557199289954,
        //   modifier: null,
        //   modifiedTm: null
        // }
      ],
      referData: [],
      //也签信息
      titleName: "",
      //新增查看弹框是否展示
      addOrEdit: false,
      copy: false,
      //按钮操作标识
      operateType: 1,
      //表单字段规则校验
      saveFormRules: {
        driverCode: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          {
            pattern: /^[0-9a-zA-Z_]{0,50}$/,
            message: "只能输入英文字母、数字、下划线",
            trigger: "blur",
          },
        ],
        driverName: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          {
            pattern: /^[\u4E00-\u9FA5A-Za-z0-9（）()\[\]【】{}]{1,40}$/,
            message: "只能输入1-40位的汉字、字母、数字或括号",
            trigger: "blur",
          },
        ],
        creator: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
        ],
        createdTm: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
        ],
      },
      //保存实体
      saveForm: {},
      copyForm: {},
      //规则引用查询
      refsearchForm: {
        page: 1,
        size: 15,
      },
      reftotal: 0,
    };
  },
  components: {
    onlyOneSearch,
    ruleForm,
  },
  created() {
    this.checkListInit();
    console.log(this.tableData, "模拟数据");
  },
  computed: {
    columnState() {
      let arr = [],
        arr1 = this.textData,
        arr2 = this.checkList;
      for (let i = 0; i < arr1.length; i++) {
        let flag = false;
        for (let j = 0; j < arr2.length; j++) {
          if (arr1[i].label == arr2[j]) {
            flag = true;
            break;
          }
        }
        arr.push(flag);
      }
      return arr;
    },
  },
  mounted() {
    this.searchFunc();
  },
  watch: {},
  methods: {
    // 点击表格行事件
    rowClick(row) {
      if (this.$refs.multipleTable) {
        this.$refs.multipleTable.clearSelection();
      }
      this.$refs.multipleTable.toggleRowSelection(row, true);
    },
    closeToQuery() {
      this.addOrEdit = false;
    },
    getDialogVisible(val) {
      this.dialogVisible = val;
    },
    refer() {
      let selected = {};
      let selectedList = this.$refs.multipleRefTable.selection;
      //不是新增必须选择一条数据
      if (selectedList.length != 1) {
        this.$message.warning("请选择一条数据!");
        return;
      }
      selected = selectedList[0];
      console.log(selected, "选中的数据");
      this.editTheData = selected;
      this.popupWindowType = "3";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.ruleDriverForm.init();
      });
    },
    checkListInit() {
      this.checkList = this.textData.map((v) => {
        return v.label;
      });
    },
    searchFunc() {
      let dataSearch = this.searchForm;
      console.log(dataSearch, "查询字段");
      console.log(this.searchForm, "参数");
      caPubDriver.pubDriverQuery(dataSearch).then((res) => {
        if (res.code === 200) {
          this.tableData = res.datas.rows;
          this.total = res.datas.total;
        }
      });
    },

    // 查看引用
    referFunc() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请选择一条数据");
      } else if (selection.length > 1) {
        return this.$message.warning("只能选择一条数据");
      } else {
        this.seeDialog = true;
        this.searchFuncConf(selection[0].driverCode);
      }
    },
    // 引用情况查询
    searchFuncConf(driverCode) {
      let data = {};
      this.$set(data, "driverCode", driverCode);
      this.$set(data, "page", "1");
      this.$set(data, "size", "10");
      console.log(data, "查询字段");
      caPubDriver.pubDriverQueryRef(data).then((res) => {
        if (res.code == 200) {
          this.referData = res.datas.rows;
          this.reftotal = res.datas.total;
        }
      });
      console.log(this.referData, "引用情况");
      console.log(this.reftotal, "数据条数");
    },

    //添加
    addOrEditFunc(val) {
      if (this.$refs.saveOrEditRef) {
        this.$nextTick(() => {
          this.$refs.saveOrEditRef.resetFields();
        });
      }

      this.titleName = "新增动因";
      this.operateType = val;
      //清空数据
      this.saveForm = {};
      let dataSearch = {};
      if (val != "1") {
        let selection = this.$refs.multipleTable.selection;
        if (val == "2") {
          this.titleName = "编辑动因";
        } else if (val == "5") {
          this.titleName = "复制动因";
        } else {
          this.titleName = "查看动因";
        }
        if (selection.length != 1) {
          return this.$message.warning("请选择一条数据");
        }
        if (val == "3") {
          this.copy = true;
        } else {
          this.addOrEdit = true;
        }
        dataSearch.driverCode = selection[0].driverCode;
      } else {
        if (val == "3") {
          this.copy = true;
        } else {
          this.addOrEdit = true;
        }
      }
      dataSearch.operateType = val;
      caPubDriver.pubDriverToForm(dataSearch).then((res) => {
        if (this.operateType == "1") {
          this.$set(this.saveForm, "creator", res.data.creator);
          this.$set(this.saveForm, "createdTm", res.data.createdTm);
        } else {
          this.saveForm = res.data;
          this.copyForm = res.data;
        }
      });
    },
    //删除数据
    deleFunc() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请选择数据进行删除");
      }
      let delData = { ids: selection.map((v) => v.driverCode) };

      caPubDriver.pubDriverCheckIsRemove(delData).then((res) => {
        if (null == res.data || "" == res.data) {
          this.$confirm("你确定要删除选中的数据吗？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              caPubDriver.pubDriverRemove(delData).then((res) => {
                if (res.code == 200) {
                  this.$message.success("删除成功");
                  this.searchFunc();
                }
              });
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消删除",
              });
            });
        } else {
          return this.$message.warning(res.data + "被规则引用不可删除");
        }
      });
    },
    //保存表单
    saveFormButton(operateType) {
      this.$refs.saveOrEditRef.validate((valid) => {
        if (valid) {
          let saveData = {};

          this.$set(saveData, "operateType", this.operateType);
          this.$set(saveData, "pubDriver", this.saveForm);
          console.log(saveData, "保存实体");
          console.log(this.saveForm, "saveForm");
          if (operateType == "2") {
            caPubDriver.pubDriverSave(saveData).then((res) => {
              this.$message({
                message: res.message,
                type: "success",
              });
              this.addOrEdit = false;
              this.searchFunc();
            });
          } else {
            caPubDriver
              .pubDriverValidateDriverCode({
                driverCode: this.saveForm.driverCode,
              })
              .then((res) => {
                if ("0" == res.data) {
                  caPubDriver.pubDriverSave(saveData).then((res) => {
                    this.$message({
                      message: res.message,
                      type: "success",
                    });
                    this.addOrEdit = false;
                    this.searchFunc();
                  });
                } else {
                  this.$message({
                    message: "此动因编码已存在",
                    type: "warning",
                  });
                }
              });
          }
        }
      });
    },
    cancelTne() {
      this.addOrEdit = false;
      this.copy = false;
    },
    timeFormat(val) {
      if (val) return moment(val).format("YYYY-MM-DD hh:MM:ss");
      else return "";
    },
    handleSizeChange(val) {
      this.searchForm.size = val;
      this.searchFunc();
      console.log(val, "每页数");
    },
    handleCurrentChange(val) {
      this.searchForm.page = val;
      this.searchFunc();
      console.log(val, "当前页");
    },
    rehandleSizeChange(val) {
      this.refsearchForm.size = val;
      this.referFunc();
      console.log(val, "每页数");
    },
    rehandleCurrentChange(val) {
      this.refsearchForm.page = val;
      console.log(val, "当前页");
      this.referFunc();
    },
  },
};
</script>

<style lang="scss" scoped></style>
